<template>
  <div class="data-dictionary-wrapper">
    <el-form :inline="true" :model="formInline">
      <el-form-item label="数据字典">
        <el-input v-model="formInline.qryWord" placeholder="请输入字典名称/编码" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchOrg">查询</el-button>
        <el-button type="primary" @click="popNewAddDialog">新增</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="20" style="height: 100%;">
      <el-col :span="5" style="height: 100%;">
        <el-scrollbar class="tree-scrollbar">
          <keep-alive>
            <CustomTree :treeData="treeData" :curNodeKey="nodeId" @nodeClick="handleClick" ref="customTree"></CustomTree>
          </keep-alive>
        </el-scrollbar>
      </el-col>
      <el-col :span="19" style="height: 100%;">
        <!-- 表格 开始 -->
        <el-table :data="tableData" v-loading="loading" :height="tableHeight" stripe>
          <el-table-column width="20"></el-table-column>
          <el-table-column label="序号" width="60">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="字典编码" prop="dictoryCode"></el-table-column>
          <el-table-column label="字典名称" prop="dictoryName"></el-table-column>
          <el-table-column label="字典值" prop="dictoryValue"></el-table-column>
          <el-table-column v-if="nodeId!=='-1'" label="描述" prop="remark"></el-table-column>
          <el-table-column v-if="nodeId!=='-1'" label="更新时间" prop="updateTime"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" icon="el-icon-edit" @click="editDetail(scope.row.dictoryId)">编辑</el-link>&nbsp;
              <el-link type="danger" :underline="false" icon="el-icon-delete" @click="deleteDetail(scope.row.dictoryId)">删除</el-link>
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格 结束 -->
      </el-col>
    </el-row>

    <!-- 对话框 开始 -->
    <el-dialog title="数据字典" :visible.sync="dialogFormVisible" width="660px" @closed="closeDialog" :close-on-click-modal="false">
      <el-form :model="dialogForm" class="dialog-form-comot" :disabled="dialogMode===CNST.READ_MODE" :rules="rules" ref="ruleDialog">
        <el-form-item label="字典编码" label-width="110px" prop="dictoryCode">
          <el-input v-model="dialogForm.dictoryCode" placeholder="请输入字典编码" :disabled="nodeId!=='-1'" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="字典名称" label-width="110px" prop="dictoryName">
          <el-input v-model="dialogForm.dictoryName" placeholder="请输入字典名称" autocomplete="off" type="textarea" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="字典值" label-width="110px" prop="dictoryValue">
          <el-input v-model="dialogForm.dictoryValue" placeholder="请输入字典值" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="nodeId!=='-1'" label="排序号" label-width="110px" prop="sequence">
          <el-input-number v-model="dialogForm.sequence" controls-position="right" :min="1"></el-input-number>
        </el-form-item>
        <el-form-item label="描述" label-width="110px" prop="remark">
          <el-input v-model="dialogForm.remark" placeholder="请输入描述" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitOrg" v-if="dialogMode!==CNST.READ_MODE">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 对话框 结束 -->
  </div>
</template>

<script>
import {
  getDictionaryList,
  addDictionary,
  deleteDictionary,
  updateDictionary,
  getDictionaryDetail
} from '@/api/systemManage'
import { deepClone } from '@/utils'
import CustomTree from './CustomTree'
export default {
  name: 'DataDictionary',
  data () {
    return {
      formInline: {
        qryWord: ''
      },
      listData: [],
      treeData: [],
      tableHeight: window.innerHeight - 200,
      loading: false,
      dialogFormVisible: false,
      dialogForm: {
        dictoryCode: '',
        dictoryName: '',
        dictoryValue: '',
        sequence: '',
        remark: ''
      },
      dialogMode: '',
      rules: {
        dictoryCode: [{ required: true, message: '请输入字典编码', trigger: 'blur' }],
        dictoryName: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
        dictoryValue: [{ required: true, message: '请输入字典值', trigger: 'blur' }],
        sequence: [{ required: true, message: '请输入排序号', trigger: 'change' }]
        // remark: [{ required: true, message: '请输入描述', trigger: 'blur' }]
      },
      nodeId: '-1', // 当前选中节点的id
      curId: ''// 当前要编辑的id
    }
  },
  computed: {
    tableData () {
      let tbData = this.listData.filter((item) => {
        return item.parentId === this.nodeId
      })
      if (tbData.length === 0) {
        return this.listData.filter((item) => {
          return item.dictoryId === this.nodeId
        })
      } else {
        return tbData
      }
    }
  },
  components: {
    CustomTree
  },
  methods: {
    // convertKeyToVal (code, arr) {
    //   arr = Array.isArray(arr) ? arr : []
    //   let resArr = arr.filter((item) => {
    //     return item.appDeployName === code
    //   })
    //   if (resArr.length === 0) {
    //     return ''
    //   }
    //   return resArr[0].appName
    // },
    getDicListShow (qryType) {
      getDictionaryList({
        qryWord: this.formInline.qryWord.trim(),
        pageSize: 100000
      }).then((res) => {
        if (!qryType) {
          this.listData = res.data.queryResult
          this.$set(this.treeData, 0, { dictoryName: '系统字典', children: [], dictoryId: '-1' })
          this.$set(this.treeData[0], 'children', this.toTree4(res.data.queryResult))
        } else {
          let resultList = deepClone(res.data.queryResult)
          let parentIdlist = [...new Set(res.data.queryResult.map(item => item.parentId))]
          // 遍历查找父节点
          if (this.formInline.qryWord !== '' && this.formInline.qryWord !== undefined) {
            this.listData.forEach(parent => {
              parentIdlist.forEach(item => {
                if (!this.inArrayId(resultList, item) && item === parent.id) {
                  resultList.push(parent)
                }
              })
            })
          }
          this.listData = resultList
          this.$set(this.treeData[0], 'children', this.toTree4(resultList))
          this.nodeId = '-1'
        }
      })
    },
    inArrayId (arr, value) {
      for (let i = 0; i < arr.length; i++) {
        if (value === arr[i].id) {
          return true
        }
      }
      return false
    },
    searchOrg () {
      this.getDicListShow('search')
    },
    refreshConf () {
    },
    // changeAppItem () {
    //   this.$set(this.formInline, 'qryWord', '')
    //   this.nodeId = '-1'
    //   this.getDicListShow()
    // },
    toTreeData (arr = []) {
      let tempArr = deepClone(arr)
      // 把每一项id作为key，该对象作为value组成一个新对象
      let obj = {}
      tempArr.forEach((item) => {
        obj[item.id] = item
      })

      let result = []
      tempArr.forEach((item) => {
        let parent = obj[item.parentId]
        if (parent) {
          (parent.children || (parent.children = [])).push(item)
        } else {
          result.push(item)
        }
      })

      return result
    },
    toTree4(data) {
      // 删除 所有 children,以防止多次调用
      data.forEach(function(item) {
        item.title = item.dictoryName
        item.key = item.dictoryId
        delete item.isLeaf
        delete item.children
      })
      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {}
      data.forEach(function(item) {
        map[item.dictoryId] = item
      })

      var val = []
      data.forEach(function(item) {
        // 以当前遍历项的pid,去map对象中找到索引的id
        var parent = map[item.parentId]
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项新增到，他对应的父级中
        if (parent) {
          (parent.children || (parent.children = [])).push(item)
        } else {
          // 如果没有在map中找到对应的索引ID,那么直接把 当前的item新增到 val结果集中，作为顶级
          val.push(item)
        }
      })
      return val
    },
    handleClick (data, node, self) {
      this.nodeId = data.dictoryId
      this.$set(this.dialogForm, 'dictoryCode' , data.dictoryCode)
    },
    popNewAddDialog () {
      this.dialogFormVisible = true
      this.dialogMode = this.CNST.ADDNEW_MODE
      let nodeArr = this.listData.filter((obj) => {
        return obj.dictoryId === this.nodeId
      })
      if (nodeArr[0]) {
        this.$set(this.dialogForm, 'dictoryCode' , nodeArr[0].dictoryCode)
      }
    },
    showToDialog (dictoryId) {
      let res = this.listData.filter(item => item.dictoryId === dictoryId)
      let data = res.length === 0 ? {} : res[0]
      for (let key in data) {
        if (this.dialogForm.hasOwnProperty(key)) {
          this.dialogForm[key] = data[key]
        }
      }
    },
    submitOrg () {
      this.$refs.ruleDialog.validate((valid) => {
        if (valid) {
          // -----------------
          let requestData = deepClone(this.dialogForm)
          if (this.dialogMode === this.CNST.ADDNEW_MODE) {
            // 新增
            requestData.parentId = this.nodeId
            addDictionary(requestData).then((res) => {
              this.$message({
                message: '新增成功',
                type: 'success'
              })
              this.getDicListShow()
              this.dialogFormVisible = false
            })
          } else if (this.dialogMode === this.CNST.EDIT_MODE) {
            // 修改
            requestData.dictoryId = this.curId
            requestData.parentId = this.listData.filter((obj) => {
              return obj.dictoryId === requestData.dictoryId
            })[0].parentId
            updateDictionary(requestData).then((res) => {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.getDicListShow()
              this.dialogFormVisible = false
            })
          }
          // -----------------
        } else {
          return false
        }
      })
    },
    editDetail (dictoryId) {
      this.dialogMode = this.CNST.EDIT_MODE
      this.dialogFormVisible = true
      this.curId = dictoryId
      this.showToDialog(dictoryId)
    },
    deleteDetail (dictoryId) {
      this.$confirm('确定删除, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        deleteDictionary({ dictoryId }).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getDicListShow()
          if (dictoryId === this.nodeId) {
            this.nodeId = '-1'
          }
        })
      })
    },
    closeDialog () {
      this.dialogMode = ''
      // 当前点击查看或编辑列表项的id置空
      this.curId = ''
      // 弹框关闭后重置表单验证
      this.$refs.ruleDialog.resetFields()
      // 清空弹框内表单数据
      for (let key in this.dialogForm) {
        this.dialogForm[key] = ''
      }
    }
  },
  created () {
  },
  mounted () {
    this.getDicListShow()
  }
}
</script>

<style lang="scss" scoped>
.data-dictionary-wrapper {
  height: calc(100vh - 100px);
  min-height: 500px;
  background-color: #ffffff;
  padding: 15px;
  box-shadow: 10px 10px 22px -2px #d2d6da;
  border-radius: 3px;
  .add-btn {
    margin-bottom: 10px;
  }
  .tree-scrollbar {
    height: calc(100% - 100px);
  }
  .btn-inline {
    margin-bottom: 14px;
  }
  .el-form.dialog-form-comot {
    .el-form-item {
      .el-select {
        width: 100%;
      }
    }
  }
  /deep/.el-scrollbar__wrap {
    overflow-x: hidden;
  }
}
</style>
<style lang="scss">
// .param-setting-wrapper {
//   .el-table {
//     .el-table__header-wrapper {
//       .el-table__header {
//         background-color: #f2f5f7;
//       }
//     }
//   }
// }
</style>
